import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'libs/database/entities/users.entity';
import { Repository } from 'typeorm';
import { ICreateUser } from './bot.dto';

@Injectable()
export class BotService {
    private readonly logger: Logger = new Logger(BotService.name);

    constructor(@InjectRepository(User) private userRepository: Repository<User>) {}

    private generateCode(): string {
        const characters = '0123456789';
        const length = 5;
        let code = '';

        for (let i = 0; i < length; i++) {
            const randomIndex = Math.floor(Math.random() * characters.length);
            code += characters.charAt(randomIndex);
        }

        return code;
    }

    async createUser(data: ICreateUser) {
        try {
            this.logger.debug(`[bot.createUser] data: ${JSON.stringify(data)}`);

            const user = await this.userRepository.findOne({
                where: { telegramId: data.telegramId },
            });
            if (!user) {
                let username = data.username || 'user';
                if (!data.username) {
                    while (true) {
                        username += this.generateCode();
                        if (!(await this.userRepository.findOne({ where: { username: username } }))) {
                            break;
                        }
                    }
                }

                await this.userRepository.save({ telegramId: data.telegramId, username: username });
                this.logger.log(`User ${data.telegramId} create`);
                return {
                    result: 'created',
                };
            }

            return;
        } catch (error) {
            this.logger.error(`[bot.createUser] error`, error);
        }
    }
}
